import React, { useEffect, useRef, useState } from "react";
import {
  Space,
  Table,
  Button,
  Modal,
  Flex,
  message,
  Upload,
  Input,
} from "antd";
import { LoadingOutlined, PlusOutlined } from "@ant-design/icons";
import { ka_img_list, delete_ka , search_ka } from "../../api";
import path from "../../api/path.jsx";

const App = () => {
  // === 状态定义区域 ===
  // 用于控制 useEffect 的执行
  const effectRan = useRef(true);
  // 存储表格数据的状态
  const [tableData, setTableData] = useState([]);

  // 上传相关的状态
  const [loading, setLoading] = useState(false); // 控制上传加载状态
  const [previewImage, setPreviewImage] = useState(""); // 存储预览图片的 URL
  const [selectedFile, setSelectedFile] = useState(null); // 存储选中的文件
  const [user_name, setUser_name] = useState(""); // 存储图片备注
  const [phone, setPhone] = useState(""); // 存储图片备注
  const [img_name, setimg_name] = useState(""); // 存储图片备注
  const [Title, setTitle] = useState(""); // 存储图片备注
  const [discounts, setDiscounts] = useState(""); // 存储图片备注

  // 修改功能相关的状态
  const [editPreviewImage, setEditPreviewImage] = useState(""); // 修改时的预览图片
  const [editSelectedFile, setEditSelectedFile] = useState(null); // 修改时选中的文件
  const [editRemark, setEditRemark] = useState(""); // 修改时的备注
  const [editUser_name, setEditUser_name] = useState(""); // 修改时的备注
  const [editPhone, setEditPhone] = useState(""); // 修改时的备注
  const [editTitle, setEditTitle] = useState(""); // 修改时的备注
  const [editDiscounts, setEditDiscounts] = useState(""); // 修改时的备注

  // 模态框相关的状态
  const [isModalOpen, setIsModalOpen] = useState(false); // 控制添加模态框显示
  const [open, setOpen] = useState(false); // 控制修改模态框显示
  const [confirmLoading, setConfirmLoading] = useState(false); // 控制确认按钮加载状态
  // 当前选中的记录
  const [currentRecord, setCurrentRecord] = useState(null);

  // 查询相关的状态
  const [searchUser_name, setSearchUser_name] = useState(""); // 存储查询的用户名称
  const [searchPhone, setSearchPhone] = useState(""); // 存储查询的用户手机号

  // === 表格列定义 ===
  const columns = [
    {
      title: "用户名称",
      dataIndex: "user_name",
      key: "user_name",
    },
    {
      title: "用户手机",
      dataIndex: "user_phone",
      key: "user_phone",
    },
    {
      title: "图片",
      dataIndex: "img",
      key: "img",
      // 自定义渲染图片列
      render: (_, record) => (
        <Space size="middle">
          <img
            src={record.img_url}
            alt="图片"
            style={{ width: "100px", height: "100px" }}
          />
        </Space>
      ),
    },
    {
      title: "名称",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "标题",
      dataIndex: "title",
      key: "title",
    },
    {
      title: "优惠",
      dataIndex: "discounts",
      key: "discounts",
    },
    {
      title: "路径",
      dataIndex: "phth",
      key: "phth",
    },
    {
      title: "操作",
      key: "operate",
      // 自定义渲染操作列
      render: (_, record) => (
        <Space size="middle">
          <a
            onClick={() => {
              // console.log(record);
              setCurrentRecord(record); // 设置当前选中的记录
              setOpen(true); // 打开修改模态框
            }}
          >
            修改
          </a>
          <a
            onClick={async () => {
              try {
                const deleteData = {
                  picUrl: record.img_url,
                };
                // 从图片URL中提取文件名
                const picUrl = JSON.stringify(deleteData);
                console.log(picUrl);

                await delete_ka(picUrl); // 只传递文件名
                message.success("删除成功");
                // 刷新表格数据
                const result = await ka_img_list();
                setTableData(
                  result.results.map((item) => ({
                    key: item.id,
                    img_url: item.img_url,
                    name: item.name || "暂无",
                    phth: item.img_url || "",
                    user_name: item.user_name || "暂无",
                    user_phone: item.user_phone || "暂无",
                    title: item.title || "暂无",
                    discounts: item.discounts || "暂无",
                  }))
                );
              } catch (error) {
                console.error("删除失败:", error);
                message.error("删除失败");
              }
            }}
          >
            删除
          </a>
        </Space>
      ),
    },
  ];

  // === 辅助函数 ===
  // 将图片转换为 Base64 格式
  const getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener("load", () => callback(reader.result));
    reader.readAsDataURL(img);
  };

  // 验证上传的图片
  const beforeUpload = (file) => {
    // 检查文件类型是否为 JPG/PNG
    const isJpgOrPng =
      file.type === "image/jpeg" ||
      file.type === "image/png" ||
      file.type === "image/webp";
    if (!isJpgOrPng) {
      message.error("只能上传 JPG/PNG 格式的图片!");
      return false;
    }
    // 检查文件大小是否小于 2MB
    const isLt2M = file.size / 1024 / 1024 < 5;
    if (!isLt2M) {
      message.error("图片大小不能超过 5MB!");
      return false;
    }
    return true;
  };

  // === 处理函数 ===
  // 处理图片上传改变事件
  const handleChange = (info) => {
    // console.log('上传事件触发:', info);
    if (info.file) {
      // console.log('文件信息:', info.file);
      if (!beforeUpload(info.file)) {
        return;
      }
      setSelectedFile(info.file);
      getBase64(info.file, (url) => {
        setPreviewImage(url);
      });
    }
  };

  // 处理修改图片上传改变事件
  const handleEditChange = (info) => {
    if (info.file) {
      if (!beforeUpload(info.file)) {
        return;
      }
      // 设置修改时选中的文件和预览图
      setEditSelectedFile(info.file);
      getBase64(info.file, (url) => {
        setEditPreviewImage(url);
      });
    }
  };

  // 处理修改确认
  const handleOk = async () => {
    setConfirmLoading(true);
    console.log(currentRecord);
    try {
      // 创建 FormData 对象
      const formData = new FormData();

      // 如果有新上传的文件，添加到 FormData
      if (editSelectedFile) {
        formData.append("photo", editSelectedFile);
      }

      // 添加原图片URL和描述
      formData.append("img_url", currentRecord.img_url);
      formData.append("name", editRemark || currentRecord.name);
      formData.append("user_name", editUser_name || currentRecord.user_name);
      formData.append("user_phone", editPhone || currentRecord.user_phone);
      formData.append("title", editTitle || currentRecord.title);
      formData.append("discounts", editDiscounts || currentRecord.discounts);
      for (let [a, b] of formData.entries()) {
        console.log(a, b);
      }
      // 发送修改请求
      const response = await fetch(`${path.path}/amend_ka`, {
        method: "POST",
        body: formData,
      });

      if (response.ok) {
        setIsModalOpen(false);
        message.success("修改成功");
        // 刷新表格数据
        const result = await ka_img_list();
        setTableData(
          result.results.map((item) => ({
            key: item.id,
            img_url: item.img_url,
            name: item.name || "暂无",
            phth: item.img_url || "",
            user_name: item.user_name || "暂无",
            user_phone: item.user_phone || "暂无",
            title: item.title || "暂无",
            discounts: item.discounts || "暂无",
          }))
        );
      } else {
        message.error("修改失败");
      }
    } catch (error) {
      console.error("修改错误:", error);
      message.error("修改出错");
    } finally {
      // 重置所有状态
      setConfirmLoading(false);
      setOpen(false);
      setUser_name("");
      setPhone("");
      setimg_name("");
      setTitle("");
      setDiscounts("");
      setPreviewImage("");
      setSelectedFile(null);
    }
  };

  const handleCancel = () => {
    setOpen(false);
    // 清空修改相关的状态
    setUser_name("");
    setPhone("");
    setimg_name("");
    setTitle("");
    setDiscounts("");
    setPreviewImage("");
    setSelectedFile(null);
  };

  // 添加图片相关
  const AddModal = () => {
    setIsModalOpen(true);
  };
  //添加
  const AddleOk = async () => {
    if (!selectedFile) {
      message.error("请先选择图片");
      return;
    }

    try {
      const formData = new FormData();
      formData.append("user_name", user_name);
      formData.append("user_phone", phone);
      formData.append("photo", selectedFile);
      formData.append("name", img_name);
      formData.append("title", Title);
      formData.append("discounts", discounts);
      for (let [a, b] of formData.entries()) {
        console.log(a, b);
      }
      const response = await fetch(`${path.path}/ka_text`, {
        method: "POST",
        // 注意：使用 FormData 时不要设置 Content-Type
        body: formData,
      });
      if (response.ok) {
        message.success("上传成功");
        setIsModalOpen(false);
        // 清空预览、文件和备注
        setUser_name("");
        setPhone("");
        setimg_name("");
        setTitle("");
        setDiscounts("");
        setPreviewImage("");
        setSelectedFile(null);
        // 刷新表格数据
        const result = await ka_img_list();
        setTableData(
          result.results.map((item) => ({
            key: item.id,
            img_url: item.img_url,
            name: item.name || "暂无",
            phth: item.img_url || "",
            user_name: item.user_name || "暂无",
            user_phone: item.user_phone || "暂无",
            title: item.title || "暂无",
            discounts: item.discounts || "暂无",
          }))
        );
      } else {
        message.error("上传失败");
      }
    } catch (error) {
      console.error("上传错误:", error);
      message.error("上传出错");
    }
  };

  const AddChang = () => {
    setIsModalOpen(false);
    // 清空预览、文件和备注
    setUser_name("");
    setPhone("");
    setimg_name("");
    setTitle("");
    setDiscounts("");
    setPreviewImage("");
    setSelectedFile(null);
  };
  // 查询
  const search = async () => {
    console.log(searchUser_name,searchPhone);
    try {
      const response = await search_ka({user_name:searchUser_name,user_phone:searchPhone});
      console.log(response);
      if(response.code == 200){
        setTableData(
          response.results.map((item) => ({
            key: item.id,
            img_url: item.img_url || "", // 使用API返回的图片URL
            name: item.name || "暂无", // 添加默认值
            phth: item.img_url || "", // 添加默认值
            user_name: item.user_name || "暂无", // 添加
            user_phone: item.user_phone || "暂无", // 添加
            title: item.title || "暂无", // 添加
            discounts: item.discounts || "暂无", // 添加
          }))
        );
      }
    } catch (error) {
      console.error("查询失败:", error);
      message.error("查询失败");
    }
  };

  // 上传按钮UI
  const uploadButton = (
    <button
      style={{
        border: 0,
        background: "none",
      }}
      type="button"
    >
      {
        // 根据加载状态显示不同的图标
        loading ? <LoadingOutlined /> : <PlusOutlined />
      }
      <div
        style={{
          marginTop: 8,
        }}
      >
        上传
      </div>
    </button>
  );

  // 数据获取
  useEffect(() => {
    // 只有当 effectRan.current 为 true 时才执行
    if (effectRan.current === true) {
      const fetchData = async () => {
        try {
          const result = await ka_img_list();
          console.log("Banner数据:", result);

          // 确保数据字段名匹配
          setTableData(
            result.results.map((item) => ({
              key: item.id,
              img_url: item.img_url || "", // 使用API返回的图片URL
              name: item.name || "暂无", // 添加默认值
              phth: item.img_url || "", // 添加默认值
              user_name: item.user_name || "暂无", // 添加
              user_phone: item.user_phone || "暂无", // 添加
              title: item.title || "暂无", // 添加
              discounts: item.discounts || "暂无", // 添加
            }))
          );
        } catch (error) {
          console.error("获取数据失败:", error);
        }
      };

      fetchData();
      // 清理函数，在组件卸载或重新执行 effect 之前运行
      return () => {
        effectRan.current = false;
      };
    }
  }, []);

  // 渲染
  return (
    <>
      <Button type="primary" style={{ marginBottom: 20 }} onClick={AddModal}>
        添加数据
      </Button>
      <br />

      <input type="text"
       placeholder="请输入用户名称" 
       value={searchUser_name}
       onChange={(e) => setSearchUser_name(e.target.value)}
       style={{margin:'0 0 20px 0px',border:'1px solid #ccc',borderRadius:'5px',padding:'7px'}}/>
      
      
      <input type="text"
       placeholder="请输入用户手机号" 
       value={searchPhone}
       onChange={(e) => setSearchPhone(e.target.value)}
       style={{margin:'0 20px 20px 20px',border:'1px solid #ccc',borderRadius:'5px',padding:'7px'}}/>
      <Button type="primary" style={{ marginBottom: 20 }} onClick={search}>
        查询
      </Button>
      <Modal
        title="修改图片信息"
        open={open}
        onOk={handleOk}
        confirmLoading={confirmLoading}
        onCancel={handleCancel}
      >
        {currentRecord && (
          <Flex gap="middle" wrap direction="column">
            <Upload
              name="photo"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              beforeUpload={() => false}
              onChange={handleEditChange}
            >
              {editPreviewImage ? (
                <img
                  src={editPreviewImage}
                  alt="预览"
                  style={{
                    width: "100%",
                  }}
                />
              ) : (
                <img
                  src={currentRecord.img_url}
                  alt="当前图片"
                  style={{
                    width: "100%",
                  }}
                />
              )}
            </Upload>
            <Input
              placeholder="请输入新的用户名"
              value={ editUser_name ||currentRecord?.user_name}
              onChange={(e) => setEditUser_name(e.target.value)}
            />
             <Input
              placeholder="请输入新的用户手机号"
              value={editPhone || currentRecord?.user_phone}
              onChange={(e) => setEditPhone(e.target.value)}
            />
             <Input
              placeholder="请输入新的图片名称"
              value={ editRemark|| currentRecord?.name}
              onChange={(e) => setEditRemark(e.target.value)}
            />
             <Input
              placeholder="请输入新的图片标题"
              value={ editTitle || currentRecord?.title}
              onChange={(e) => setEditTitle(e.target.value)}
            />
             <Input
              placeholder="请输入新的优惠策略"
              value={ editDiscounts || currentRecord?.discounts}
              onChange={(e) => setEditDiscounts(e.target.value)}
            />
          </Flex>
        )}
      </Modal>
      <Modal
        title="上传数据"
        open={isModalOpen}
        onOk={AddleOk}
        onCancel={AddChang}
      >
        <Flex gap="middle" wrap direction="column">
          <Upload
            name="photo"
            listType="picture-card"
            className="avatar-uploader"
            showUploadList={false}
            beforeUpload={() => false}
            onChange={handleChange}
          >
            {previewImage ? (
              <img
                src={previewImage}
                alt="预览"
                style={{
                  width: "100%",
                  height: "100%",
                  objectFit: "cover",
                }}
              />
            ) : (
              uploadButton
            )}
          </Upload>
          <Input
            placeholder="请填写用户名称"
            value={user_name}
            onChange={(e) => setUser_name(e.target.value)}
          />
          <Input
            placeholder="请填写用户手机号"
            value={phone}
            onChange={(e) => setPhone(e.target.value)}
          />
          <Input
            placeholder="请填写图片名称"
            value={img_name}
            onChange={(e) => setimg_name(e.target.value)}
          />
          <Input
            placeholder="请填写图片标题"
            value={Title}
            onChange={(e) => setTitle(e.target.value)}
          />
          <Input
            placeholder="请填写图片优惠"
            value={discounts}
            onChange={(e) => setDiscounts(e.target.value)}
          />
        </Flex>
      </Modal>
      <Table columns={columns} dataSource={tableData} />
    </>
  );
};

export default App;
